package com.alpha.common.utils.storage;

import com.alpha.module.sys.dao.SysMerchantMapper;
import com.alpha.module.sys.entity.SysMerchant;
import com.alpha.common.utils.CommonUtils;
import com.alpha.common.utils.Constants;
import com.alpha.common.utils.SpringBeanUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.CreateBucketRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * 腾讯cos 存储服务
 * @author zhaojiulin
 * @DATE 2020/2/27 13:34
 */

@Component
public class TencentCos {

    private final StorageProperties storageProperties;
    private final COSClient cosClient;

    @Autowired
    public TencentCos(StorageProperties properties) {
        storageProperties = properties;
        COSCredentials cred = new BasicCOSCredentials(storageProperties.getTencentCosSet().getSecretId(), storageProperties.getTencentCosSet().getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region(storageProperties.getTencentCosSet().getRegion()));
        cosClient = new COSClient(cred, clientConfig);
    }



    /**
     * 存储桶创建
     */
    public void cosCreateBucket(String bucketName) {
        boolean b = cosClient.doesBucketExist(bucketName);
        if (!b) {
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
            try {
                cosClient.createBucket(createBucketRequest);
                cosClient.shutdown();
            } catch (CosClientException serverException) {
                serverException.printStackTrace();
            }
        }
    }

    /**
     * 文件上传
     * @param cosFile 文件
     * @param key key
     * @return
     */
    public String cosUploadFile(File cosFile, String key) {
        initBucketName();
        return cosUploadFile(new PutObjectRequest(storageProperties.getTencentCosSet().getBucketName(), key, cosFile));
    }

    public String cosUploadFile(InputStream inputStream, String key) {
        initBucketName();
        return cosUploadFile(new PutObjectRequest(storageProperties.getTencentCosSet().getBucketName(), key, inputStream, new ObjectMetadata()));
    }

    public String cosUploadFile(PutObjectRequest putObjectRequest) {
        cosClient.putObject(putObjectRequest);
        cosClient.shutdown();
        Date date = new Date(System.currentTimeMillis() + 5 * 60 * 10000);
        URL url = cosClient.generatePresignedUrl(storageProperties.getTencentCosSet().getBucketName(), putObjectRequest.getKey(), date);
        if (url == null) {
            return "";
        }
        return "https://" + storageProperties.getTencentCosSet().getBucketName() + ".cos.ap-shanghai.myqcloud.com/" + putObjectRequest.getKey();
    }

    /**
     * 根据商户
     * 初始化存储桶
     */
    private void initBucketName() {
        String merchantId = CommonUtils.getLocalData(Constants.MERCHANT_ID);
        if (!"".equals(merchantId)) {
            long mchId = Long.parseLong(merchantId);
            // mchId为1 是系统用户，使用默认存储桶
            if (mchId > 1) {
                SysMerchantMapper sysMerchantMapper = SpringBeanUtil.getBean(SysMerchantMapper.class);
                SysMerchant sysMerchant = null;
                if (sysMerchantMapper != null) {
                    sysMerchant = sysMerchantMapper.selectByPrimaryKey(mchId);
                }
                if (sysMerchant != null) {
                    storageProperties.getTencentCosSet().setBucketName(sysMerchant.getMerchantCode() + "-" + storageProperties.getTencentCosSet().getAppId());
                }
                cosCreateBucket(storageProperties.getTencentCosSet().getBucketName());
            }
        }
    }
}
